#-*- coding:utf8 -*-
import pickle
import uuid

class Session:
    __path = ''
    __settings = {}
    
    @staticmethod
    def getVersion():
        return 'v0.0.1'
    
    @classmethod
    def setPath(cls, path):
        cls.__path = path
        
    def __init__(self, req = None):
        if req <> None:
            id = req.get_cookie('PYSESSIONID', None)
            if id == None:
                id = uuid.uuid1()
                s = "%s" % id 
                req.set_cookie('PYSESSIONID', s)
        else:
            id = uuid.uuid1()
        self.__filename = "%s/%s" %(self.__path, id)
        self.__fp = open(self.__filename, 'ab+')
        try:
            self.__fp.seek(0, 0)
            line = self.__fp.read()
            if len(line) <> 0:
                self.__settings = pickle.loads(line)
        except:
            pass
        
    def get(self, key):
        return self.__settings.get(key, None)
        
    def put(self, key, value):
        self.__settings[key] = value
    
    def unset(self, key):
        del self.__settings[key]
            
    def destroy(self):
        self.__settings.clear()
        
    def __del__(self):
        try:
            s = pickle.dumps(self.__settings)
            self.__fp.truncate(0)
            self.__fp.write(s)
            self.__fp.flush()
        except:
            pass
        finally:
            self.__fp.close()
        